#! /usr/bin/env python
# -*- coding: utf-8 -*-
import time
import os
import re
import json

import FileHostProtoType
from ..utility.gadget import cutstr



class tbitem(FileHostProtoType.HostItem):
    def __init__(self, name, type, code, link='', encrypt_name='', server_name=''):
        FileHostProtoType.HostItem.__init__(self, name, type, code, link, encrypt_name, server_name)
    
class turbobit(FileHostProtoType.FileHostProcess):            
    def __init__(self, user, pwd):
        FileHostProtoType.FileHostProcess.__init__(self)
        self.hostname = "TurboBit" 
        self._opener = None
        self._user = user
        self._pwd = pwd
        self.islogin = False
        self.isanoy = False
        self.logtype = 'poster'
        self._cookieCurl = '%s_%s.cookie' % (self._user, self.hostname)
        self._cookieCurl = os.path.join(os.path.dirname(__file__), self._cookieCurl)
        
    def login(self):
        '''
        login to MediaFire
        return opener object which includes cookies
        '''
        self.generateOpener() 
        if self.islogin:
            return True
#        if self.restore_cookiejar():
#            return True
        
        #set english UI
        self.post_request("http://turbobit.net/lang/en") 
        
        self.fherr.write('login to TurboBit %s/%s...' % (self._user,'*'*len(self._pwd)))
        
        #post login request
        loginData = {'user[submit]' : 'Login', 
                'user[login]' : self._user, 
                'user[pass]' : self._pwd,
                'user[memory]' : 'on'}
        loginresult =  self.loginFileHost("http://turbobit.net/user/login", loginData)
        
        indexpage = self.post_request("http://turbobit.net/")
        #you always see you username at the top of the page, if it logins successfully.
        if self._user.lower() not in indexpage.lower():
            self.fherr.write(loginresult)
            self.fherr.write("User %s Failed to Login TurboBit." % self._user)
            return False
        self.fherr.write("User %s logined." % self._user)
        self.islogin = True
        #self._cj.save(self._cookieCurl, ignore_discard=True)
        return True

    def check_cookie(self):
        self.fherr.write('Checking Cookie...')
        response = self.post_request("http://turbobit.net/")
        if response and self._user in response:
            self.fherr.write("User %s Status : Logined." % self._user)
            self.islogin = True             
            return True
        self.fherr.write(response)
        self.fherr.write("[%s]User %s Status : not Logined." % (time.ctime(), self._user))
        return False  
    
    def restore_cookiejar(self):
        '''
        load cookie file, then access website to verify if cookie is avaiable
        '''
        if os.path.isfile(self._cookieCurl):
            self.fherr.write('Restore Local Cookie.')
            try:
                self._cj.load(self._cookieCurl, ignore_discard=True)
            except:
                self.fherr.write('Failed to Restore Local CookieJar.')
            #access website to confirm cookie is avaiable
            return self.check_cookie()
        return False
        
    def upload_web(self, file, progressLog=None, other_args=None, send_range=None):
        return self.upload_web_local_register(file, progressLog, other_args, send_range)
        
    def upload_web_local_register(self, file, progressLog=None, other_args=None, send_range=None):
        indexpage = self.post_request("http://turbobit.net/")
        
        urlsite = self.get_upload_key(indexpage, "urlSite", -1, 'urlSite=')
        urlsite = urlsite[:urlsite.find('&')]
        userid = self.get_upload_key(indexpage, "userId", -1, 'userId=')
        userid = userid[:userid.find('&')]
        apptype = self.get_upload_key(indexpage, "apptype", -1, 'apptype=')
        apptype = apptype[:apptype.find('"')]
        
        callback = None
        if progressLog is not None:
            callback = progressLog.write
        filesize = os.path.getsize(file)
        filename = self.rename_func(file)
        start_point = 0
        info = "Uploading...%s" % file
        if send_range is not None:
            #range is a 3-tuple, <start, end, number>
            filesize = send_range[1] - send_range[0] + 1
            filename += ".%03d" % send_range[2]
            start_point = send_range[0]
            info += " part%d" % send_range[2]
        
        self.fherr.write(info) 
        fileobj = open(file, 'rb')
        fileobj.seek(start_point)  
        data = {'Filedata' : fileobj,
                'Filename' : filename,
                'stype' : 'null',
                'apptype' : apptype,
                'user_id' : userid,
                'id' : 'null'}
        
        uploadurl = urlsite
        upload_response = self.post_request(uploadurl, data, cb=callback, \
                                            setfilename=filename,\
                                            setfilesize=filesize)
        content = json.loads(upload_response)
        if "Everything is ok" in upload_response: 
            
            code = content["id"]
            basename = os.path.basename(file) 
            item = tbitem(basename, 'file', 
                          code, 
                          "http://turbobit.net/%s/%s.html" % (code, filename), 
                          filename)
            self.newupload.append(item)      
            return item
        else:
            #it seems something wrong >__<
            self.fherr.write("upload url: {}\n".format(uploadurl)) 
            self.fherr.write("upload response: {}\n".format(upload_response)) 
            self.fherr.write("Message: %s" % content['message']) 
            self.fherr.write("Failed to get key after uploaded for %s" % file)
            return 